from django.shortcuts import render
from django.views import View
from django.http import HttpResponse,HttpResponseRedirect
import jsonpickle
from cartapp.cartmanager import DBCartManger
import uuid
import datetime
from userapp.models import *
from orderapp.models import *
from goodsapp.models import *
from utils.alipay_p3 import *
from django.db.models import F

# Create your views here.

def toOrderView(request):

    cartitems = request.GET.get('cartitems','')
    # 获取总金额
    totalPrice = request.GET.get('totalPrice','')

    # 判断当前用户是否登录
    if not request.session.get('user',''):
        return render(request,'login.html',{'reflag':'order','cartitems':cartitems,'totalPrice':totalPrice})
    
    # 将获取到的cartitems转型
    cartitemList = jsonpickle.loads(cartitems)
    # [{'goodsid':'1','colorid':'1','sizeid':'1'},{},{}]
    # print('cartitemList:'+cartitemList)

    # 获取默认收货地址
    user = jsonpickle.loads(request.session.get('user',''))
    addrObj = user.address_set.get(isdefault=True)

    # 获取订单内容
    cartItemObjList = [ DBCartManger(user).get_cartitems(**item) for item in cartitemList if item ]

    
    return render(request,'order.html',{'cartItemObjList':cartItemObjList,'addrObj':addrObj,'totalPrice':totalPrice})



alipayObj = AliPay(appid='9021000143676918', 
                   app_notify_url='http://127.0.0.1:8000/order/checkPay/', 
                   app_private_key_path='orderapp/keys/my_private_key.txt',
                   alipay_public_key_path='orderapp/keys/alipay_public_key.txt', 
                   return_url='http://127.0.0.1:8000/order/checkPay/', 
                   debug=True
            )

def toPay(request):
    # 获取请求参数
    addrid = request.GET.get('address',-1)
    payway = request.GET.get('payway','alipay')
    cartitems = request.GET.get('cartitems','')
    totalPrice = request.GET.get('totalPrice',0)

    params = {
        'out_trade_num' : uuid.uuid4().hex,
        'order_num' : datetime.now().strftime('%Y%m%d%H%M%S'),
        'address' : Address.objects.get(id=addrid),
        'user' : jsonpickle.loads(request.session.get('user','')),
        'payway' : payway
    }

    orderObj = Order.objects.create(**params)

    if cartitems:    
        # '[{"goodsid":"1","colorid":"1","sizeid":"1"},{}]'
        cartitemList = jsonpickle.loads(cartitems)
        
        orderItemList = [ OrderItem.objects.create(order=orderObj,**item) for item in cartitemList if item]

    urlparams = alipayObj.direct_pay(subject='京东商城', out_trade_no=orderObj.out_trade_num, total_amount=totalPrice)
    
    # 拼接url地址
    url = alipayObj.gateway + '?' + urlparams

    return HttpResponseRedirect(url)


def checkPay(request):
    # 获取所有的请求参数
    params = request.GET.dict()

    # 获取sign的值
    sign = params.pop('sign')

    if alipayObj.verify(params, sign):
        # 获取当前登录用户
        user = jsonpickle.loads(request.session.get('user',''))

        # 修改订单的状态
        orderObj = Order.objects.get(out_trade_num=params.get('out_trade_no',''))
        orderObj.trade_no = params.get('trade_no','')
        orderObj.status = '待发货'
        orderObj.save()

        # # 修改库存
        # orderItemList = orderObj.orderitem_set.all()
        # for oi in orderItemList:
        #     try:
        #         # 获取对应的 Goods, Color, Size 对象
        #         goods = Goods.objects.get(id=oi.goodsid)
        #         color = Color.objects.get(id=oi.colorid)
        #         size = Size.objects.get(id=oi.sizeid)
                
        #         # 使用 Goods, Color, Size 对象查询 Inventory
        #         inventory = Inventory.objects.get(goods=goods, color=color, size=size)
                
        #         # 更新库存数量
        #         Inventory.objects.filter(id=inventory.id).update(count=F('count') - oi.count)

        #     except (Goods.DoesNotExist, Color.DoesNotExist, Size.DoesNotExist, Inventory.DoesNotExist) as e:
        #         print(f"Error: {e}")

        # 修改库存
        orderItemList = orderObj.orderitem_set.all()
        [ Inventory.objects.filter(goods_id=oi.goodsid,color_id=oi.colorid,size_id=oi.sizeid).update(count=F('count')-oi.count) for oi in orderItemList if oi]

        # 更新购物车表中的数据
        [ user.cartitem_set.filter(goodsid=oi.goodsid,colorid=oi.colorid,sizeid=oi.sizeid,count=oi.count).delete() for oi in orderItemList if oi]

        return HttpResponse('支付成功!')
    
    return HttpResponse('支付失败！')


